﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Properties;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace BrnMall.Web.Framework
{
    public class ApiResult: ActionResult
    {
        public object Data { get; set; }
        [JsonIgnore]
        public ExceptionCode ExceptionCode { get; set; }
        public int Code{get{return (int) ExceptionCode; }
        }
        /// <summary>
        /// 获取或设置 错误消息, 默认没有错误为String.Empty
        /// </summary>
        /// <remarks></remarks>
        public string Message { get; set; }
        /// <summary> 获取或设置 当前服务器时间
        /// </summary>
        /// <remarks></remarks>
        public DateTime ServerTime { get; set; }
        public ApiResult(object data)
        {
            ExceptionCode = ExceptionCode.None;
            Message = "";
            ServerTime = DateTime.Now;
            this.Data = data;
        }
        public ApiResult(object data,ExceptionCode code)
        {
            ExceptionCode = code;
            Message = "";
            ServerTime = DateTime.Now;
            this.Data = data;
        }
        public ApiResult(object data, ExceptionCode code,string message)
        {
            ExceptionCode = code;
            Message = message;
            ServerTime = DateTime.Now;
            this.Data = data;
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.Write(JsonConvert.SerializeObject(this, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
        }
    }
    
}
